import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;


public class SendEmail {
	JTextField firstInput;
	JTextField secondInput;
	String username = null;
	String password = null;
	String filepath = System.getProperty("user.home")+"\\EasyFTP";
	
	public SendEmail(String user, String pass){
		username = user;
		password = pass;
		
	}
	
	void makeFrame(){
		final JFrame frame = new JFrame();
		JPanel panel = new JPanel(new GridLayout(2,1));
		JPanel input = new JPanel(new GridLayout(5,1));
		JPanel buttons = new JPanel(new GridLayout(2,2));
		JLabel first = new JLabel("Please Enter Receiver's Email:");
		firstInput = new JTextField();
		JLabel second = new JLabel("Please re-enter email:");
		secondInput = new JTextField();
		JButton submit = new JButton("Submit");
		JButton cancel = new JButton("Cancel");
		JButton noVis = new JButton("");
		input.add(first);
		input.add(firstInput);
		input.add(second);
		input.add(secondInput);
		buttons.add(submit);
		buttons.add(noVis);
		buttons.add(cancel);
		buttons.add(noVis);
		noVis.setVisible(false);
		panel.add(input);
		panel.add(buttons);
		frame.add(panel);
		frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		frame.setLocationRelativeTo(null);
		frame.setTitle("Reciever's Email");
		submit.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent arg0) {
				if(checkEmail(firstInput.getText(), secondInput.getText())){
					sendMail();
					frame.dispose();
					JOptionPane.showMessageDialog(frame, "Email Sent to receiver");
					ConnectionSetup conn = new ConnectionSetup();
					int port = conn.getPort();
					ServerSideSocket socket = new ServerSideSocket(port);
					socket.createSocket();
					
				}
				else{
					JOptionPane.showMessageDialog(frame, "Emails entered do not match, please try again");
					firstInput.setText("");
					secondInput.setText("");
					firstInput.requestFocus();
				}
			}
			
		});
		//Makes it so the Enter key can be used to submit data
		secondInput.addKeyListener(new KeyListener(){
			@Override
			public void keyPressed(KeyEvent arg0) {
				if(arg0.getKeyChar() == KeyEvent.VK_ENTER){
					if(checkEmail(firstInput.getText(), secondInput.getText())){
						sendMail();
						frame.dispose();
						JOptionPane.showMessageDialog(frame, "Email Sent to receiver");
						ConnectionSetup conn = new ConnectionSetup();
						int port = conn.getPort();
						ServerSideSocket socket = new ServerSideSocket(port);
						socket.createSocket();
					}
					else{
						JOptionPane.showMessageDialog(frame, "Emails entered do not match, please try again");
						firstInput.setText("");
						secondInput.setText("");
						firstInput.requestFocus();
					}
				}
			}

			@Override
			public void keyReleased(KeyEvent arg0) {
				// TODO Auto-generated method stub
			}
			@Override
			public void keyTyped(KeyEvent arg0) {
				// TODO Auto-generated method stub
			}
		});
		cancel.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent e) {
				frame.dispose();
			}
		});
		frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		frame.setVisible(true);
		frame.setSize(350,250);
		//Set to the middle of the screen
		frame.setLocationRelativeTo(null);
	}
	
	public boolean checkEmail(String s, String r){
		if(s.equals(r)){
			return true;
		}
		return false;
	}
	
	
	/**
	 * Code taken from http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/ and
	 * http://www.jguru.com/faq/view.jsp?EID=30251
	 */
	public void sendMail(){
		//Need to get the computer's IP and port number, this will be used later
		ConnectionSetup con = new ConnectionSetup();
		String ip = con.getIP();
		String port = EasyFTP.port1.getText();
		//Properties for the connection to GMail's Servers
		Properties props = new Properties();
		props.put("mail.smtp.host", "smtp.gmail.com");
		props.put("mail.smtp.socketFactory.port", "465");
		props.put("mail.smtp.socketFactory.class",
				"javax.net.ssl.SSLSocketFactory");
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.port", "465");
		//Start a new session with the username and password entered from LoginPrompt
		Session sesh = Session.getInstance(props,new javax.mail.Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(username,password);
			}
		});
		try {
			Message message = new MimeMessage(sesh);
			message.setFrom(new InternetAddress(username));
			message.setRecipients(Message.RecipientType.TO,
					InternetAddress.parse(firstInput.getText()));
			message.setSubject("Easy FTP Request");
			//Because we're going to add an attachment the actual body of the message is just part of the process
			MimeBodyPart part = new MimeBodyPart();
			part.setText("Hello,\n\nPlease save the attachment and upload it into the Easy FTP program.");
			//Create the attachment
			File file = new File("Setup.txt");
			try {
				//If the file already exists, delete it
				if(file.exists())
					file.delete();
				file.createNewFile();
				FileWriter stream = new FileWriter(file);
				BufferedWriter out = new BufferedWriter(stream);
				//Write the IP address and port number being used to the file
				out.write(ip+"\n"+port+"\n"+EasyFTP.privKey);
				out.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			//Create the multiple part message
			Multipart mp = new MimeMultipart();
			//Add the body to it
			mp.addBodyPart(part);
			//Create the attachment part of the message
			MimeBodyPart messageAttachment = new MimeBodyPart();
			//Select the source of the attachment, in our case the file we created above
			DataSource attachment = new FileDataSource(file);
			messageAttachment.setDataHandler(new DataHandler(attachment));
			messageAttachment.setFileName("Setup.txt");
			//Add it to the multiple part message
			mp.addBodyPart(messageAttachment);
			//Add both parts of the message to the original message
			message.setContent(mp);
			//Send it away
			Transport.send(message);
 
		} catch (MessagingException e) {
			throw new RuntimeException(e);
		}
		
	}
	
}
